package com.example.demo.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class MyGatewayFilter extends ZuulFilter {

    /*4种过滤器类型,
　　pre：可以在请求被路由之前调用,
　　route：在路由请求时候被调用,
　　post：在route和error过滤器之后被调用,
　　error：处理请求时发生错误时被调用*/

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
        //获取token参数
        Object accessToken = request.getParameter("token");
        if (accessToken == null) {
//            log.warn("token is empty");
//            //过滤该请求, 不对其进行路由
//            ctx.setSendZuulResponse(false);
//            //返回错误码
//            ctx.setResponseStatusCode(401);
//            //返回错误内容
//            ctx.setResponseBody("token is null!");
            //Zuul还未对返回数据做处理
            return null;
        }
        return null;
    }

    @Override
    public int compareTo(ZuulFilter filter) {
        return super.compareTo(filter);
    }
}
